const FUN = require('../comm/func');
const rCache = require('../model/redis_cache');
const dbHelp = require('../comm/db-helper');
const timLib = require('../comm/time-lib');
const PMR = require('../utils/policyManger');

module.exports = class Template
{
  //将数据库选项缓存到redis
  //policy 来自数据库的记录，附加了user_auth user_level字段
  //opts 数据库json字段的解析对象
  //CacheCallback 存储执行函数
  static InitCache(policy,opts,CacheCallback)
  {
    let obj=PMR.baseParam(policy);//即将缓存到redis的参数

    //检查json选项
    if( parseInt(policy.record_limit)==0 ||
        parseInt(opts.fetch_period)==0 )
    {
      console.error('wrong template params',policy.id);
      return false;
    }

    //json options参数存储
    obj.fetch_period = opts.fetch_period;//采样周期
    obj.cache_expire = Number(opts.fetch_period)+60;//数据缓存reids有效期
    obj.record_limit = policy.record_limit;//数据库条数上限

    //数据库处理
    dbHelp.createTab(obj.table,policy.uid);

    //缓存主站参数
    obj.hwid = policy.master;
    obj.role = 'master';
    obj.brother = policy.brother;
    CacheCallback(policy.id,policy.master,obj);//记录到缓存

    //开启定时器
    PMR.setSecInter(obj.policy_id,obj.fetch_period);
  }//end InitCache

  //处理json数据
  // topic = {project,devType,func,devId}
  // dConf即InitCache中的obj
  // dataBuf即mq消息内容，buf对象
  static async DataIn(topic, dConf, dataBuf)
  {
    if(topic.func!='var') return;

    let stamp=timLib.NowStamp();
    let preStamp=timLib.Rounding(dConf.fetch_period,stamp);
    let nodeDevStamp=PMR.rdNode(dConf)+':'+preStamp;

    return;
  }

  //周期回调
  static SecInter(dConf,nowStamp)
  {
    let preStamp=timLib.Rounding(dConf.fetch_period,nowStamp);
    let nodeDevStamp=PMR.rdNode(dConf)+':'+preStamp;

    pcyLog('[%d] secInter timer',dConf.policy_id,timLib.NowStr());


    //返回false可结束定时器
  }



}